import { Outlet, useNavigate } from "react-router-dom";
import type { MenuTheme, MenuProps, DropdownProps } from "antd";
import { useState } from "react";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  AppstoreOutlined,
  DashboardOutlined,
  VideoCameraOutlined,
  ChromeFilled,
  ForkOutlined,
  SendOutlined,
  AppstoreAddOutlined,
} from "@ant-design/icons";
import { Layout, Menu, Button, theme, Avatar, Dropdown } from "antd";
import styles from "@/assets/styles/modules/home.module.scss";
import {
  LightIcon,
  DarkIcon,
  GPUIcon,
  CPUIcon,
  MotherboardIcon,
  MemoryIcon,
  HDDIcon,
  SSDIcon,
} from "@/components/icon/index.tsx";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import {
  changeThemeColor,
  changeBorderState,
} from "@/store/modules/themeStore";

const { Header, Sider, Content } = Layout;

type MenuItem = Required<MenuProps>["items"][number];

function getItem(
  label: React.ReactNode,
  key?: React.Key | null,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: "group"
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}

const itemsMeum: MenuItem[] = [
  getItem("仪表盘", "/dashboard", <DashboardOutlined />),

  getItem("配件信息", "/accinfo", <AppstoreOutlined />, [
    getItem("显卡", "/accinfo/gpu", <GPUIcon />),
    getItem("CPU", "/accinfo/cpu", <CPUIcon />),
    getItem("主板", "/accinfo/center", <MotherboardIcon />),
    getItem("内存", "/accinfo/memory", <MemoryIcon />),
    getItem("固态硬盘", "/accinfo/ssd", <SSDIcon />),
    getItem("机械硬盘", "/accinfo/hdd", <HDDIcon />),
  ]),

  getItem("组装教程", "/video", <VideoCameraOutlined />),

  getItem("其他应用", "/other", <ForkOutlined />, [
    getItem("交流论坛", "/other/chat", <SendOutlined />),
    getItem("资源推荐", "/other/resource", <AppstoreAddOutlined />),
  ]),
];

const items: MenuProps["items"] = [
  {
    label: "用户信息",
    key: "1",
  },
  {
    label: "系统说明",
    key: "2",
  },
  {
    label: "退出登录",
    key: "3",
  },
];

const Home = () => {
  const themeColor = useAppSelector((state) => state.theme.themeColor);
  const borderColor = useAppSelector((state) => state.theme.borderColor);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  let defaultKeys = ""; //默认选中的导航栏

  const determineRoute = () => {
    if (window.location.pathname.includes("/accinfo")) {
      defaultKeys = "/accinfo";
    } else if (window.location.pathname.includes("/other")) {
      defaultKeys = "/other";
    }
  };
  determineRoute();

  
  

  const [OpenKeys] = useState<string[]>([defaultKeys]);

  //获取用户昵称
  const user_name = localStorage.getItem("blogToken");

  const {
    token: { colorBgContainer, borderRadiusLG, colorText }, //获取主题颜色
  } = theme.useToken();
  const [collapsed, setCollapsed] = useState(false); //控制导航栏的展开和收起
  const [Theme] = useState<MenuTheme>("light"); //控制导航栏的主题颜色
  const [logo, setLogo] = useState(false); //控制logo的展开和收起
  const [open, setOpen] = useState(false);

  const handleOpenChange: DropdownProps["onOpenChange"] = (nextOpen, info) => {
    if (info.source === "trigger" || nextOpen) {
      setOpen(nextOpen);
    }
  };

  //切换主题
  const changeTheme = () => {
    dispatch(changeThemeColor(!themeColor));
    if (themeColor) {
      dispatch(changeBorderState("#F5F5F5"));
    } else {
      dispatch(changeBorderState("#000000"));
    }
  };

  // 存储主题

  //导航栏收缩时，logo的展开和收起
  const changeCollapsed = () => {
    setCollapsed(!collapsed);
    if (!collapsed) {
      setLogo(true);
    } else {
      setTimeout(() => {
        setLogo(false);
      }, 100);
    }
  };

  //导航栏点击跳转
  const toPage = (e: any) => {
    navigate(e.key);
  };

  return (
    <Layout style={{ height: "100vh" }}>
      <Sider
        theme={Theme}
        trigger={null}
        collapsible
        collapsed={collapsed}
        className={styles.nav}
      >
        <div>
          <div className={styles.logo}>
            <div>
              <ChromeFilled style={{ fontSize: "24px", color: colorText }} />
              {!logo && <span style={{ color: colorText }}>后台管理系统</span>}
            </div>
          </div>

          <Menu
            mode="inline"
            defaultSelectedKeys={[window.location.pathname]}
            defaultOpenKeys={OpenKeys}
            items={itemsMeum}
            onClick={toPage}
          />
        </div>
        <div style={{ display: "flex", justifyContent: "center" }}>
          <Button
            type={Theme === "light" ? "default" : "primary"}
            shape="circle"
            icon={!themeColor ? <DarkIcon /> : <LightIcon />}
            size="large"
            onClick={changeTheme}
          />
        </div>
      </Sider>

      <Layout style={{ background: borderColor, color: colorText }}>
        <Header
          style={{
            padding: 0,
            color: colorText,
            paddingRight: 100,
            background: colorBgContainer,
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          <Button
            type="text"
            icon={
              collapsed ? (
                <MenuUnfoldOutlined style={{ color: colorText }} />
              ) : (
                <MenuFoldOutlined style={{ color: colorText }} />
              )
            }
            onClick={changeCollapsed}
            style={{
              fontSize: "16px",
              width: 64,
              height: 64,
            }}
          />
          <div>
            <Dropdown
              menu={{ items }}
              onOpenChange={handleOpenChange}
              open={open}
            >
              <div className={styles.user}>
                <Avatar>
                  {user_name === "" ? "U" : user_name?.charAt(0).toUpperCase()}
                </Avatar>
                <span className={styles.username}>{user_name || "User"}</span>
              </div>
            </Dropdown>
          </div>
        </Header>
        <Content
          style={{
            margin: "20px 16px",
            padding: 15,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default Home;
